﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SharePointPowerToys.BusinenssObjects;

namespace SharePointPowerToys
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:ConfigurationChooser runat=server></{0}:ConfigurationChooser>")]
    public class ConfigurationChooser : WebControl, INamingContainer
    {
        public event EventHandler Click;
        protected void OnClick(EventArgs e)
        {
            Click(SettingOptions.getItemFromKey(ddl.SelectedValue), e);
        }

        public DropDownList ddl;
        Button btn;

        public override ControlCollection Controls
        {
            get
            {
                EnsureChildControls();
                return base.Controls;
            }
        }

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Text
        {
            get
            {
                return collectionEngineScript();
                String s = (String)ViewState["Text"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["Text"] = value;
            }
        }

        public SortableCollection<SettingOption> SettingOptions
        {
            get;
            set;
        }

        public string SelectedSettingKey
        {
            get;
            set;
        }

        private string collectionEngineScript()
        {

            StringBuilder sScript = new StringBuilder();

            sScript.Append("<script language=\"jscript\" type=\"text/jscript\">\n");
            sScript.Append("function CreateCollection(ClassName)    \n");
            sScript.Append("{\n");
            sScript.Append("    var obj=new Array();\n");
            sScript.Append("    eval(\"var t=new \"+ClassName+\"()\");\n");
            sScript.Append("    for(_item in t)\n");
            sScript.Append("        {\n");
            sScript.Append("            eval(\"obj.\"+_item+\"=t.\"+_item);\n");
            sScript.Append("        }\n");
            sScript.Append("    return obj;\n");
            sScript.Append("}\n");

            sScript.Append("function InfoCollection()\n");
            sScript.Append("{\n");
            sScript.Append("    this.Container=\"\";\n");
            sScript.Append("    this.Add=function(obj)\n");
            sScript.Append("    {\n");
            sScript.Append("        this.push(obj);\n");
            sScript.Append("    }\n");
            sScript.Append("        this.Item=function(key)\n");
            sScript.Append("    {\n");
            sScript.Append("        for(i=0;i<this.length;i++)\n");
            sScript.Append("        {\n");
            sScript.Append("            if(this[i].getKey()==key)\n");
            sScript.Append("            {\n");
            sScript.Append("                return this[i];\n");
            sScript.Append("            }\n");
            sScript.Append("        }\n");
            sScript.Append("    }\n");
            sScript.Append("}\n");

            sScript.Append("function Info(key, imageSrc, moreLink, description) {\n");
            sScript.Append("    this._key = key;\n");
            sScript.Append("    this._imageSrc = imageSrc;\n");
            sScript.Append("    this._moreLink = moreLink;\n");
            sScript.Append("    this._description = description;\n");
            sScript.Append("}\n");

            sScript.Append("Info.prototype.setKey  = function(val) {\n");
            sScript.Append("    this._key = val;\n");
            sScript.Append("}\n");

            sScript.Append("Info.prototype.getKey = function() {\n");
            sScript.Append("    return this._key;\n");
            sScript.Append("}\n");

            sScript.Append("Info.prototype.setImageSrc  = function(val) {\n");
            sScript.Append("    this._imageSrc = val;\n");
            sScript.Append("}\n");

            sScript.Append("Info.prototype.getImageSrc = function() {\n");
            sScript.Append("    strTemp = \"\";\n");
            sScript.Append("    if(this._imageSrc != \"\")\n");
            sScript.Append("    {\n");
            sScript.Append("        strTemp = '<img src=\"' + this._imageSrc + '\" width=\"125px\" align=\"left\" border=\"0\"/>';\n");
            sScript.Append("    }\n");
            sScript.Append("    return strTemp;\n");
            sScript.Append("}\n");

            sScript.Append("Info.prototype.setMoreLink  = function(val) {\n");
            sScript.Append("    this._moreLink = val;\n");
            sScript.Append("}\n");

            sScript.Append("Info.prototype.getMoreLink = function() {\n");
            sScript.Append("    strTemp =\"\";\n");
            sScript.Append("    if(this._moreLink != \"\")\n");
            sScript.Append("    {\n");
            sScript.Append("        strTemp = ' <a href=\"' + this._moreLink + '\">More</A>';\n");
            sScript.Append("    }\n");
            sScript.Append("    return strTemp;\n");
            sScript.Append("}\n");

            sScript.Append("Info.prototype.setDescription  = function(val) {\n");
            sScript.Append("    this._description = val + ' ';\n");
            sScript.Append("}\n");

            sScript.Append("Info.prototype.getDescription = function() {\n");
            sScript.Append("    return this._description;\n");
            sScript.Append("}\n");

            sScript.Append("function setText(objInfo){\n");
            sScript.Append("    document.getElementById('myText').innerHTML = objInfo.getImageSrc() + objInfo.getDescription() + objInfo.getMoreLink();\n");
            sScript.Append("}\n");

            sScript.Append("</script>\n");


            return sScript.ToString();

        }

        protected override void OnPreRender(EventArgs e)
        {
            if (Page.ClientScript.IsClientScriptBlockRegistered("collectionEngine") == false)
            {
                Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "collectionEngine", collectionEngineScript());
            }

            if (Page.ClientScript.IsClientScriptBlockRegistered("collectionInfo") == false)
            {
                Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "collectionInfo", collectionInfoScript());
            }

            if (Page.ClientScript.IsStartupScriptRegistered("initDescription") == false)
            {
                Page.ClientScript.RegisterStartupScript(typeof(Page), "initDescription", initDescriptionScript());
            }

            if (Page.ClientScript.IsStartupScriptRegistered("resetSelectBoxWhenPQFieldIsEdited") == false)
            {
                Page.ClientScript.RegisterStartupScript(typeof(Page), "resetSelectBoxWhenPQFieldIsEdited", resetSelectBoxWhenPQFieldIsEdited());
            }


            base.OnPreRender(e);

        }

        private string initDescriptionScript()
        {
            StringBuilder sScript = new StringBuilder();

            sScript.Append("<script language=\"javascript\" type=\"text/javascript\">\n");

            sScript.Append("setText(infoCollection.Item(document.getElementById(\"" + this.ddl.ClientID + "\").options[document.getElementById(\"" + this.ddl.ClientID + "\").selectedIndex].value));");


            sScript.Append("</script>\n");

            return sScript.ToString();

        }

        private string collectionInfoScript()
        {

            StringBuilder sScript = new StringBuilder();

            sScript.Append("<script language=\"javascript\" type=\"text/javascript\">\n");

            sScript.Append("infoCollection=new CreateCollection(\"InfoCollection\");     \n");

            //sScript.Append("infoCollection.Add(new Info(1,\"asdf.jpg\",\"http://google.com\",\"google Rocks\"));\n");
            //sScript.Append("infoCollection.Add(new Info(2,\"asdf2.jpg\",\"http://google2.com\",\"google Rocks2 adsf asdf adsdf adsf asddf adsdf asddf as dfdf adsfdadfdfadfd asdf a adfas fdaf\"));\n");
            //sScript.Append("infoCollection.Add(new Info(3,\"asdf3.jpg\",\"http://google3.com\",\"google Rocks3\"));\n");
            //sScript.Append("infoCollection.Add(new Info(5,\"asdf3.jpg\",\"http://google3.com\",\"google Rocks3\"));\n");
            foreach (SettingOption s in SettingOptions)
            {
                sScript.Append("infoCollection.Add(new Info(\"" + s.Key + "\",\"" + s.Image + "\",\"" + s.More + "\",\"" + s.Description + "\"));\n");
            }
            sScript.Append("</script>\n");

            //sScript.Append("<select id=\"Select1\" onblur=\"setText(infoCollection[this.options[this.selectedIndex].value]);\">\n");
            //sScript.Append("    <option value=\"1\">foo1</option>\n");
            //sScript.Append("    <option value=\"2\">foo2</option>\n");
            //sScript.Append("    <option value=\"3\">foo3</option>\n");
            //sScript.Append("    <option value=\"4\">foo4</option>\n");
            //sScript.Append("    <option value=\"5\">foo5</option>\n");
            //sScript.Append("</select>\n");
            //sScript.Append("<button>Set</button>\n");
            //sScript.Append("<p id=\"myText\"></p>\n");

            return sScript.ToString();
        }

        private string resetSelectBoxWhenPQFieldIsEdited()
        {
            //loops through every input element on the page and gets the ones who have "editorzone_edit" in the name, then checks further to see if
            //it's a field that we are interested in.  If it is then it attaches an event (msie only) for onClick and OnKKeyDown 
            //to flip the select box to a "Custom" state.
            StringBuilder sScript = new StringBuilder();

            sScript.Append("<script language=\"javascript\" type=\"text/javascript\">\n");
            sScript.Append("var pqElement = false;  // assume it's not a powerquery Web Part\n");
            sScript.Append("var returnArr = document.getElementsByTagName(\"input\");\n");
            sScript.Append("                for(i=0;i<returnArr.length;i++){\n");
            sScript.Append("                    element = returnArr[i];\n");
            sScript.Append("                    if(element.id.toLowerCase().indexOf(\"editorzone\") > 0){\n");
            sScript.Append("                        pqElement = isPQElement(element, \"DataProviderAssemblyClass_EDITOR\", pqElement);\n");
            sScript.Append("                        pqElement = isPQElement(element, \"DataProviderParameters_EDITOR\", pqElement);\n");
            sScript.Append("                        pqElement = isPQElement(element, \"SiteUrl_EDITOR\", pqElement);\n");
            sScript.Append("                        pqElement = isPQElement(element, \"CacheSourceSeconds_EDITOR\", pqElement);\n");

            sScript.Append("                        pqElement = isPQElement(element, \"XslTransformFile_EDITOR\", pqElement);\n");
            sScript.Append("                        pqElement = isPQElement(element, \"ShowRefreshTime_EDITOR\", pqElement);\n");
                        
            sScript.Append("                        if (pqElement)\n");
            sScript.Append("                        {\n");
            //sScript.Append("                            element.attachEvent('onclick', resetSelect);\n");
            sScript.Append("                            element.attachEvent('onchange', resetSelect);\n");
            //sScript.Append("                            element.attachEvent('onkeydown', resetSelect);\n");
            sScript.Append("                            //alert(\"Is PQ Element id:\" + element.id);\n");
            sScript.Append("                        }\n");
            sScript.Append("                        else\n");
            sScript.Append("                        {\n");
            sScript.Append("                            //alert(\"Not PQ Element id:\"+ element.id);\n");
            sScript.Append("                        }\n");
            sScript.Append("                    }\n");
            sScript.Append("                }\n");


            sScript.Append("function isPQElement(element, PQFieldName, isAlready)\n");

            sScript.Append("{\n");

            sScript.Append("     return (element.id.toLowerCase().indexOf(PQFieldName.toLowerCase() > 0) || isAlready);\n");

            sScript.Append("}\n");

            

            sScript.Append("function resetSelect()");
            sScript.Append("{");
            sScript.Append("    document.getElementById(\"" + ddl.ClientID + "\").selectedIndex = 0;");
            sScript.Append("}");


            sScript.Append("</script>\n");
            return sScript.ToString();

        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            ddl.RenderControl(output);
            //btn.RenderControl(output);
            new LiteralControl("<p id=\"myText\"></p>\n").RenderControl(output);
            
            output.Write(Text);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
        }

        protected override void CreateChildControls()
        {
            Controls.Clear();
            mySelect();
            myButton();
            Controls.Add(ddl);
            //Controls.Add(btn);
            EnsureChildControls();
            base.CreateChildControls();
            
        }

        private Control mySelect()
        {
            ddl = new DropDownList();
            ddl.Attributes["onChange"] = "setText(infoCollection.Item(this.options[this.selectedIndex].value));";
            foreach (SettingOption s in SettingOptions)
            {
                ddl.Items.Add(new ListItem(s.Title, s.Key));
            }

            ddl.SelectedValue = this.SelectedSettingKey;
            return ddl;
        }

        private Control myButton()
        {
            btn = new Button();
            btn.Text = "Set";
            btn.Click += new EventHandler(btn_Click);

            return btn;

            
        }

        void btn_Click(object sender, EventArgs e)
        {
            this.Click(sender, e);
            btn.Text = "di it";
        }


        
    }
}
